import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class ToyHash {
	MessageDigest md;
	int digestSize;
	
	public ToyHash(String algorithm, int digestSize) {
		try {
			md = MessageDigest.getInstance(algorithm);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		this.digestSize = digestSize;
	}
	
	public int digest(int message) {
		byte[] bytes = ByteBuffer.allocate(4).putInt(message).array();
		md.update(bytes);
		byte byteData[] = md.digest();
		String result = "";
		for (int i = 0; i < 3; i++) {
			result += (Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
		}
		return (int)(Integer.parseInt(result, 16) % Math.pow(2, digestSize));
	}
	
	public String digest(String message) {
		byte[] bytes = message.getBytes();
		md.update(bytes);
		byte byteData[] = md.digest();
		String result = "";
		for (int i = 0; i < byteData.length; i++) {
			result += (Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
		}
		return result;
	}
	
	public static void main(String[] args) {
		ToyHash hash = new ToyHash("SHA-1", 160);
    	System.out.println(hash.digest("ffffffffffffffffNo one has completed lab 2 so give them all a 0"));
    	//e7f8a6061db607270c2251a2e16b641ccaff0732
    }
}
